import { createRouter, createWebHistory } from 'vue-router';
import { useUserStore } from '../stores/user';

// 导入视图组件
const Login = () => import('../views/Login.vue');
const DoctorHome = () => import('../views/DoctorHome.vue');
const PatientHome = () => import('../views/PatientHome.vue');
const ImageUpload = () => import('../views/ImageUpload.vue');
const AiReview = () => import('../views/AiReview.vue');
const Reports = () => import('../views/Reports.vue');
const DiagnosisProgress = () => import('../views/DiagnosisProgress.vue');

const routes = [
  {
    path: '/',
    redirect: '/login'
  },
  {
    path: '/login',
    name: 'Login',
    component: Login,
    meta: { requiresAuth: false }
  },
  // 注册页面路由暂时移除，因为组件不存在
  {
    path: '/doctor-home',
    name: 'DoctorHome',
    component: DoctorHome,
    meta: { requiresAuth: true, roles: ['doctor'] }
  },
  {
    path: '/patient-home',
    name: 'PatientHome',
    component: PatientHome,
    meta: { requiresAuth: true, roles: ['patient'] }
  },
  {
    path: '/image-upload',
    name: 'ImageUpload',
    component: ImageUpload,
    meta: { requiresAuth: true, roles: ['doctor'] }
  },
  {
    path: '/ai-review',
    name: 'AiReview',
    component: AiReview,
    meta: { requiresAuth: true, roles: ['doctor'] }
  },
  {
    path: '/reports',
    name: 'Reports',
    component: Reports,
    meta: { requiresAuth: true, roles: ['patient'] }
  },
  {
    path: '/diagnosis-progress',
    name: 'DiagnosisProgress',
    component: DiagnosisProgress,
    meta: { requiresAuth: true, roles: ['patient'] }
  }
];

const router = createRouter({
  history: createWebHistory(),
  routes
});

// 路由守卫
router.beforeEach((to, from, next) => {
  const userStore = useUserStore();
  
  // 不需要认证的页面直接放行
  if (!to.meta.requiresAuth) {
    return next();
  }
  
  // 检查是否已登录
  if (!userStore.isAuthenticated) {
    return next('/login');
  }
  
  // 检查角色权限
  if (to.meta.roles && !to.meta.roles.includes(userStore.userRole)) {
    // 根据用户角色重定向到对应首页
    if (userStore.userRole === 'doctor') {
      return next('/doctor-home');
    } else if (userStore.userRole === 'patient') {
      return next('/patient-home');
    }
  }
  
  next();
});

export default router;